package com.smartian.v2;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.smartian.v2.model.ScheduleTaskBean;
import com.smartian.v2.utils.DateTimeResultFilter;
import com.smartian.v2.utils.TextRenderHandler;

/**
 * 本例子为demo
 */
public class AsrTextHandler {
    private Context context;
    public AsrTextHandler(Context context){
        this.context = context.getApplicationContext();
    }

    public  AsrParserResult handle(String source) {
        if (TextUtils.isEmpty(source)) {
            return null;
        }
        long startTime = System.currentTimeMillis();
        AbstractTextParser parser = TextParserFactory.createParser(source);
        ScheduleTaskBean scheduleTask = parser.getScheduleTaskBean();

        Log.e("AsrReminder", "handle cost time ==>" + (System.currentTimeMillis() - startTime) + "," + source);
        if (scheduleTask == null) {
            Log.e("AsrReminder", "解析失败");
            handleAsrErrorPhase();
            return null;
        }
        String dateTime = scheduleTask.getDateTime();
        String dateformat = scheduleTask.getDateTimeFormat();

        if (shouldDisplayError(dateTime, dateformat)) {
            Log.e("AsrReminder", "无效语句");
            handleAsrErrorPhase();
            return null;
        }
        int repeatType = DateTimeResultFilter.getScheduleTaskRepeatType(scheduleTask);
        if (repeatType == -1) {
            handleAsrErrorPhase();
            return null;
        }
        String closestDateTime = DateTimeResultFilter.getClosestDateTime(scheduleTask);
        if (TextUtils.isEmpty(closestDateTime)) {
            handleAsrErrorPhase();
            Log.e("AsrReminder", "准确时间无法推定");
            return null;
        }
        AsrParserResult result = new AsrParserResult();
        String subject = DateTimeResultFilter.findSubject(scheduleTask.getSourceText(), scheduleTask);

        if (TextUtils.isEmpty(subject)) {
            handleAsrErrorPhase();
            Log.e("AsrReminder", "纯日期时间，无效解析");
            return null;
        }
        result.setResultInfo(scheduleTask);
        result.setSource(source);
        result.setSubjectName(subject);
        result.setRemark(scheduleTask.getSourceText());
        result.setRepeatType(repeatType);
        result.setRepeatTime(closestDateTime);
        OpLog.e("AsrReminder", "--habitBean>" + result);
        CharSequence subjectHtmlText = TextRenderHandler.getInstance().getResultContent(context, scheduleTask);
        result.setSubjectHtmlText(subjectHtmlText);
        return result;
    }

    private static void handleAsrErrorPhase() {
        Log.e("AsrReminder", "解析失败");
    }
    private static boolean shouldDisplayError(String dateTime, String dateformat) {
        return TextUtils.isEmpty(dateTime) || TextUtils.isEmpty(dateformat);
    }
}
